import React from 'react';
import { Card, Table, Button, Input, Modal, Form, Space, Tag, Image, Select, message } from 'antd';

// 产品列表页面（模仿 admin-web 的 Product.vue）
export default function Product() {
  // 搜索与分页
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ name: '', typeName: '', no: '', order: undefined, sort: undefined });
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [loading, setLoading] = React.useState(false);

  // 标签集合（模拟）
  const [productTags, setProductTags] = React.useState([
    { id: 1, name: '热销' },
    { id: 2, name: '新品' },
    { id: 3, name: '限时' },
  ]);

  // 列表数据（模拟）
  const [list, setList] = React.useState(() => ([
    { id: 1, typeName: '饮料', name: '可乐', goodsTags: [{ id: 1, name: '热销' }], no: 'P1001', costPrice: 3.5, url: 'https://via.placeholder.com/60', num: 120, createTime: '2025-09-10 12:00' },
    { id: 2, typeName: '饮料', name: '雪碧', goodsTags: [{ id: 2, name: '新品' }], no: 'P1002', costPrice: 3.5, url: 'https://via.placeholder.com/60', num: 86, createTime: '2025-09-12 08:30' },
    { id: 3, typeName: '零食', name: '薯片', goodsTags: [{ id: 3, name: '限时' }], no: 'P2001', costPrice: 5.5, url: 'https://via.placeholder.com/60', num: 65, createTime: '2025-09-15 16:20' },
  ]));

  // 新增/编辑
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [form] = Form.useForm();
  const [editing, setEditing] = React.useState(null);

  // 过滤
  const filtered = React.useMemo(() => {
    let data = list;
    if (search.name) data = data.filter(i => String(i.name).includes(search.name));
    if (search.typeName) data = data.filter(i => String(i.typeName).includes(search.typeName));
    if (search.no) data = data.filter(i => String(i.no).includes(search.no));
    // 排序
    if (search.sort) {
      const dir = search.order === 'asc' ? 1 : -1;
      data = [...data].sort((a, b) => {
        const va = a[search.sort];
        const vb = b[search.sort];
        if (typeof va === 'number' && typeof vb === 'number') return (va - vb) * dir;
        return String(va).localeCompare(String(vb)) * dir;
      });
    }
    return data;
  }, [list, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  const columns = [
    { title: '产品类型', dataIndex: 'typeName', width: 160, align: 'center', sorter: true },
    { title: '商品名称', dataIndex: 'name', width: 200, align: 'center', sorter: true },
    {
      title: '标签',
      dataIndex: 'goodsTags',
      width: 190,
      align: 'center',
      render: (tags) => (
        <span>
          {tags?.map((t, idx) => (
            <Tag key={idx} color="blue" style={{ marginRight: 5 }}>{t.name}</Tag>
          ))}
        </span>
      )
    },
    { title: '编码', dataIndex: 'no', width: 120, align: 'center' },
    { title: '价格', dataIndex: 'costPrice', width: 120, align: 'center', sorter: true },
    {
      title: '图片',
      dataIndex: 'url',
      width: 130,
      align: 'center',
      render: (url) => <Image src={url} width={60} height={60} />,
    },
    { title: '销量', dataIndex: 'num', width: 80, align: 'center', sorter: true },
    { title: '创建时间', dataIndex: 'createTime', align: 'center' },
    {
      title: '操作',
      fixed: 'right',
      width: 160,
      align: 'center',
      render: (_, row) => (
        <Space>
          <Button size="small" onClick={() => onEdit(row)}>编辑</Button>
          <Button size="small" danger onClick={() => onDelete(row)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 搜索
  const onSearchSubmit = async () => {
    const values = await searchForm.validateFields();
    setSearch(prev => ({ ...prev, ...values }));
    setPageIndex(1);
  };
  const onResetSearch = () => {
    searchForm.resetFields();
    setSearch({ name: '', typeName: '', no: '', order: undefined, sort: undefined });
    setPageIndex(1);
  };

  // 排序事件
  const onTableChange = (pagination, filters, sorter) => {
    if (sorter && sorter.order) {
      setSearch(prev => ({ ...prev, sort: sorter.field, order: sorter.order === 'ascend' ? 'asc' : 'desc' }));
    } else {
      setSearch(prev => ({ ...prev, sort: undefined, order: undefined }));
    }
  };

  // 弹窗增改删
  const onAdd = () => {
    setEditing(null);
    form.resetFields();
    setDialogOpen(true);
  };
  const onEdit = (row) => {
    setEditing(row);
    form.setFieldsValue({
      typeName: row.typeName,
      name: row.name,
      goodsTags: row.goodsTags?.map(t => t.id),
      no: row.no,
      costPrice: row.costPrice,
      url: row.url,
      notes: row.notes,
    });
    setDialogOpen(true);
  };
  const onDelete = (row) => {
    setList(prev => prev.filter(i => i.id !== row.id));
    message.success('删除成功');
  };
  const onSave = async () => {
    const values = await form.validateFields();
    const tags = (values.goodsTags || []).map(id => productTags.find(t => t.id === id)).filter(Boolean);
    if (editing) {
      setList(prev => prev.map(i => i.id === editing.id ? { ...i, ...values, goodsTags: tags } : i));
      message.success('商品已更新');
    } else {
      const maxId = Math.max(0, ...list.map(i => i.id));
      setList(prev => [{ id: maxId + 1, createTime: new Date().toLocaleString(), num: 0, ...values, goodsTags: tags }, ...prev]);
      message.success('商品已新增');
    }
    setDialogOpen(false);
  };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Card variant="borderless">
        <Form form={searchForm} layout="inline" initialValues={search} style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <Form.Item name="typeName" label="产品类型">
            <Input allowClear placeholder="如：饮料/零食" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="name" label="商品名称">
            <Input allowClear placeholder="请输入名称" style={{ width: 200 }} />
          </Form.Item>
          <Form.Item name="no" label="编码">
            <Input allowClear placeholder="商品编码" style={{ width: 160 }} />
          </Form.Item>
          <Space>
            <Button type="primary" onClick={onSearchSubmit}>查询</Button>
            <Button onClick={onResetSearch}>重置</Button>
            <Button type="dashed" onClick={onAdd}>新增商品</Button>
          </Space>
        </Form>
      </Card>

      <Card title="产品列表" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pageData}
          columns={columns}
          pagination={{
            current: pageIndex,
            pageSize,
            total: filtered.length,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            onChange: (pi, ps) => { setPageIndex(pi); setPageSize(ps); },
          }}
          onChange={onTableChange}
        />
      </Card>

      <Modal title={editing ? '编辑商品' : '新增商品'} open={dialogOpen} onOk={onSave} onCancel={() => setDialogOpen(false)} width={600}>
        <Form form={form} layout="vertical">
          <Form.Item name="typeName" label="产品类型" rules={[{ required: true, message: '请输入产品类型' }]}> 
            <Input placeholder="例如：饮料" />
          </Form.Item>
          <Form.Item name="name" label="商品名称" rules={[{ required: true, message: '请输入商品名称' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="goodsTags" label="商品标签"> 
            <Select mode="multiple" allowClear placeholder="选择标签">
              {productTags.map(t => <Select.Option key={t.id} value={t.id}>{t.name}</Select.Option>)}
            </Select>
          </Form.Item>
          <Form.Item name="no" label="编码"> 
            <Input />
          </Form.Item>
          <Form.Item name="costPrice" label="价格"> 
            <Input type="number" step="0.01" />
          </Form.Item>
          <Form.Item name="url" label="图片地址"> 
            <Input placeholder="图片 URL" />
          </Form.Item>
          <Form.Item name="notes" label="备注"> 
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}